import React, { useRef, useState, useMemo, useCallback } from 'react';
import { Title } from '@/components/common';
import { isEmpty } from 'lodash';
import { Header, Grid } from 'gantd';
import type { OnReady } from 'gantd/lib/grid';
import classnames from 'classnames';
import type { SearchFormSchema, SearchFormRef } from '@/components/searchform';
import SearchForm from '@/components/searchform';
import type { Pageinfo, GridTransferInnerProps, Direction, OnSearch } from './index';
import CustomRender from './CustomRender';
import { useSizeHeight, formatGridColumns, getFilterDateSource } from './utils';
import styles from './index.less';
import { commonText } from '@/utils/utils';

interface TransferItemProps {
  transKey: string;
  direction: Direction;
  height: number | string;
  schema?: SearchFormSchema;
  disabled: boolean;
  columns?: any[];
  dataSource: any[];
  selectedRows: any[];
  rowKey: any;
  filterKey?: string;
  filterValue?: string;
  innerProps: GridTransferInnerProps;
  searchRef: { current: SearchFormRef };
  onSelect: (selectedRows: any[]) => void;
  onGridReady: OnReady;
  onSearch?: OnSearch;
  onRowDragEnter: (direction: Direction, params: any) => void;
  onRowDrag: (...args: any[]) => void;
  defaultExportParams: any;
}

export type SizeType = 'searchForm' | 'beforeSearch' | 'afterSearch' | 'afterGrid';

// const SelectedText = (props: { length: number }) => <span className={styles.selectedText}>（{tr(`已选中{0}个`,props.length)}）</span>

const DEFAULT_OBJECT = {};
const HEADER_HEIGHT = 31;
const BORDER = 2;
const INIT_BASE_SIZE = {
  width: 0,
  height: 0,
};
const INIT_SIZE = {
  searchForm: INIT_BASE_SIZE,
  beforeSearch: INIT_BASE_SIZE,
  afterSearch: INIT_BASE_SIZE,
  afterGrid: INIT_BASE_SIZE,
};

/**
 * 穿梭框的左/右项
 */
export default (props: TransferItemProps) => {
  const {
    transKey,
    direction,
    height,
    schema,
    disabled,
    columns,
    dataSource,
    selectedRows,
    rowKey,
    filterKey,
    filterValue,
    innerProps,
    onSelect,
    onGridReady,
    searchRef,
    onSearch,
    onRowDragEnter,
    onRowDrag,
    defaultExportParams,
  } = props;

  const {
    title,
    loading,
    pagination,
    extraSearchProps = DEFAULT_OBJECT,
    extraGridProps = DEFAULT_OBJECT,
    beforeSearch,
    afterSearch,
    afterGrid,
    filterKey: directionFilterKey,
  } = innerProps;

  const currentSchema = extraSearchProps.schema || schema;
  const showSearchForm = !isEmpty(currentSchema);
  // const searchRef = useRef({} as SearchFormRef)
  const [size, setSize] = useState(INIT_SIZE);
  const sizeRef = useRef(size);
  const otherHeight = useSizeHeight(size);
  const pageRef = useRef({} as Pageinfo);

  const currentFilterKey = directionFilterKey || filterKey;

  // const title_ = useMemo(() => {
  //   return (<>
  //     {title}
  //     <SelectedText length={selectedRows.length} />
  //   </>)
  // }, [title, selectedRows.length])

  // 计算table高度
  const tableHeight = useMemo(() => {
    return `calc(${typeof height === 'number' ? height + 'px' : height} - ${
      BORDER + otherHeight + (showSearchForm ? 0 : HEADER_HEIGHT)
    }px)`;
  }, [height, otherHeight]);

  const extraGridProps_ = useMemo(() => {
    const base = {
      rowBuffer: 50,
      suppressMoveWhenRowDragging: true, // 阻止拖拽中就交换顺序
      enableMultiRowDragging: true, // 允许多行拖拽
      ...extraGridProps,
      rowDragManaged: !disabled,
      rowSelection: !disabled,
    };
    let extra: any = {};

    if (base.rowDragManaged) {
      extra = {
        onRowDragEnter: onRowDragEnter.bind(null, direction),
        onRowDragEnd: onRowDrag,
      };
    }

    return {
      ...base,
      ...extra,
    };
  }, [extraGridProps, disabled, onRowDragEnter, onRowDrag]);

  const showDataSource = useMemo(() => {
    return getFilterDateSource(dataSource, currentFilterKey, filterValue);
  }, [dataSource, currentFilterKey, filterValue]);

  const gridColumns: any[] = useMemo(() => {
    let gridColumns: any[] = extraGridProps.columns || columns;
    gridColumns = formatGridColumns(gridColumns, disabled, direction);
    return gridColumns;
  }, [extraGridProps.columns, columns, disabled]);

  const rowSelection = useMemo(() => {
    if (disabled) return null;
    return {
      ...(extraGridProps_.rowSelection || {}),
      selectedRows,
      onSelect: (selectedRowKeys: string[], rows: any[]) => {
        onSelect(rows);
      },
    };
  }, [disabled, extraGridProps_.rowSelection, selectedRows]);

  const pagination_ = useMemo(() => {
    if (isEmpty(pagination)) return;
    const { pageSize, beginIndex, total } = pagination as any;
    pageRef.current = {
      beginIndex: 0,
      pageSize,
    };
    return {
      beginIndex,
      pageSize,
      total,
      onChange: (beginIndex: number, pageSize: number) => {
        pageRef.current = {
          beginIndex: beginIndex,
          pageSize,
        };
        const {
          current: { search },
        } = searchRef;
        if (search) {
          search();
        } else {
          onSearch && onSearch(direction, {}, pageRef.current);
        }
      },
    };
  }, [pagination]);

  const onResize = useCallback((size, sizeType: SizeType) => {
    const currentSize = sizeRef.current;
    const newSize = {
      ...currentSize,
      [sizeType]: size,
    };
    setSize(newSize);
    sizeRef.current = newSize;
  }, []);

  const onSearch_ = useCallback(
    (direction: Direction, params: any) => {
      onSearch && onSearch(direction, params, pageRef.current);
    },
    [onSearch],
  );

  return (
    <div className={classnames(styles.tranferItem, { [styles['grid-without-pagi']]: !pagination_ })}>
      <CustomRender content={beforeSearch} onResize={(size) => onResize(size, 'beforeSearch')} />
      {showSearchForm && (
        <>
          <SearchForm
            {...extraSearchProps}
            searchKey={transKey + direction}
            ref={searchRef}
            schema={currentSchema}
            title={<Title title={commonText.smartSearchTitleText} />}
            headerProps={{
              type: 'line',
            }}
            onSearch={onSearch_.bind(null, direction)}
            onSizeChange={(size) => onResize(size, 'searchForm')}
          />
        </>
      )}
      <CustomRender content={afterSearch} onResize={(size) => onResize(size, 'afterSearch')} />
      {/* {
        !showSearchForm && (
          <Header title={tr("查询")} type="line"/>
        )
      } */}
      <Header title={title} type="line" />
      <Grid
        hideMenuItemExport
        {...extraGridProps_}
        loading={loading}
        height={tableHeight}
        rowkey={rowKey}
        columns={gridColumns}
        dataSource={showDataSource}
        rowSelection={rowSelection}
        pagination={pagination_}
        suppressCsvExport
        defaultExportParams={defaultExportParams}
        onReady={onGridReady}
        hideSelcetedBox
      />
      <CustomRender content={afterGrid} onResize={(size) => onResize(size, 'afterGrid')} />
    </div>
  );
};
